//
//  MainViewController.m
//  PurchasingMeeting
//
//  Created by zhuang yihang on 7/11/13.
//  Copyright (c) 2013 YX. All rights reserved.
//

#import "MainViewController.h"
#import "SuitViewController.h"
#import "ProductViewController.h"
#import "AnalysisViewController.h"
#import "StatisticViewController.h"
#import "HelpViewController.h"
#import "WebServiceManager.h"
#import "WaitTooles.h"
#import "SettingmatchViewController.h"
#import "FPPopoverController.h"
#import "TipView.h"
#import "OrdermessageView.h"
#import "AdministratorViewController.h"

#import "Reachability.h"

#import "PMGlobal.h"

#import "DataManager.h"
#import "UIHelper.h"
#import "config.h"
#import "AppManager.h"

@interface MainViewController (){
    BOOL hasSetupUI_;
}

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
       // [self setNavTitle:@"首页"];
        if ([[PMGlobal getInstance] networkFlag]) {
            [[AppManager sharedManager] startAutoSubmitSession];
            [[AppManager sharedManager] startAutoUpdateSession];
        }
        
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(app_has_expired) name:@"app_has_expired" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(show:) name:@"show" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shoprefresh:) name:@"shoprefresh" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ordernumrefresh:) name:@"ordernumrefresh" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showtip:) name:@"showtip" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(set:) name:@"set" object:nil];
        
        hasSetupUI_ = NO;
    }
    return self;
}

- (void)dealloc{
    [[AppManager sharedManager] stopAutoUpdate];
    [[AppManager sharedManager] stopAutoSubmit];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    newshops = [[NSMutableArray alloc]init];
    UIView *v = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:v];
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    [v addGestureRecognizer:tapGr];
    
    UserObject *userobj = [[DataManager sharedManager]getUserObject];
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setObject:userobj.userCode forKey:@"username"];
    [def setObject:userobj.password forKey:@"password"];
    [def synchronize];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
    UIButton *b1 = [UIButton buttonWithType:UIButtonTypeCustom];
#ifdef DHH_iOS
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"main_logout_iphone.png"];
#else
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"main_logout_ipad.png"];
#endif
    [b setImage:img forState:UIControlStateNormal];
    b.frame = CGRectMake(10, 10, img.size.width, img.size.height);
    [b addTarget:self action:@selector(ret) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithCustomView:b];
    self.navigationItem.leftBarButtonItem = left;
    
    img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    [b1 setBackgroundImage:img forState:UIControlStateNormal];
    b1.frame = CGRectMake(10, 10, img.size.width+20, img.size.height);
    b1.tag=13;
    [b1 setTitle:@"切换店铺" forState:UIControlStateNormal];
    [b1 addTarget:self action:@selector(shops:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:b1];
    
    img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    
    
//#ifdef SHOP_VERIFY_ENABLE
//    /*
//    UIButton *b2 = [UIButton buttonWithType:UIButtonTypeCustom];
//    [b2 setBackgroundImage:img forState:UIControlStateNormal];
//    b2.frame = CGRectMake(700, 10, img.size.width+20, img.size.height);
//    [b2 setTitle:@"店铺检查" forState:UIControlStateNormal];
//    b2.titleLabel.adjustsFontSizeToFitWidth = YES;
//    [b2 addTarget:self action:@selector(b2click:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *shopcheck = [[UIBarButtonItem alloc] initWithCustomView:b2];
//    
//    UIButton *b3 = [UIButton buttonWithType:UIButtonTypeCustom];
//    [b3 setBackgroundImage:img forState:UIControlStateNormal];
//    b3.frame = CGRectMake(700, 10, img.size.width+20, img.size.height);
//    [b3 setTitle:@"店铺审核" forState:UIControlStateNormal];
//    b3.titleLabel.adjustsFontSizeToFitWidth=YES;
//    [b3 addTarget:self action:@selector(b3click:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *shopveri = [[UIBarButtonItem alloc] initWithCustomView:b3];
//    NSArray *arr = [[NSArray alloc]initWithObjects:right,shopcheck,shopveri, nil];
//     */
//#else
//    NSArray *arr = [[NSArray alloc]initWithObjects:right, nil];
//#endif
     NSArray *arr = [[NSArray alloc]initWithObjects:right, nil];
    
    self.navigationItem.rightBarButtonItems = arr;
    
    shop = [[DataManager sharedManager]getShopList];
    NSArray *array = [NSArray array];
    array = [shop sortedArrayUsingComparator:^NSComparisonResult(ShopObject *a,ShopObject *b){
        if ([a.bOrder boolValue]==NO&&[b.bOrder boolValue]==YES) {
            return NSOrderedDescending;
        }
        else if([a.bOrder boolValue]==YES&&[b.bOrder boolValue]==NO)
        {
            return NSOrderedAscending;
        }
        else if([a.bOrder boolValue]==YES&&[b.bOrder boolValue]==YES)
        {
            if (a.bCheck==1&&b.bCheck==0) {
                return NSOrderedDescending;
            }
            else if(a.bCheck==0&&b.bCheck==1)
            {
                return NSOrderedAscending;
            }
        }
        return NSOrderedSame;
    }];
    [newshops removeAllObjects];
    for (NSString *str in array) {
        [newshops addObject:str];
    }
    [[DataManager sharedManager] setShopList:newshops];
}

- (void)updateOrder{

    if (![[PMGlobal getInstance] networkFlag]) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh"
                                                           object:nil];
        return;
    }
    
    [[AppManager sharedManager] pauseAutoSubmitSession];
    [[AppManager sharedManager] pauseAutoUpdateSession];
    [WaitTooles showHUD:@"更新订单"];
    
    [[AppManager sharedManager] forceSubmitOrder:^(id res){
        if (res!=nil) {
            [[DataManager sharedManager] updateOrder:^(id res){
                [WaitTooles removeHUD];
                
                [[AppManager sharedManager] startAutoSubmitSession];
                [[AppManager sharedManager] startAutoUpdateSession];
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh"
                                                                   object:nil];
            }];
        }else{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh"
                                                               object:nil];
            [WaitTooles removeHUD];
        }
        
    }];
    
}

-(void)ret
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您是否要退出这个账户?" message:nil delegate:self cancelButtonTitle:@"是" otherButtonTitles:@"否", nil];
    [alert show];
    alert.tag = 503;
    //[self.navigationController setNavigationBarHidden:YES];
}

- (void)back{
    [[AppManager sharedManager] stopAutoUpdate];
    [[AppManager sharedManager] stopAutoSubmit];
    [orderview removeFromSuperview];
    
    [self removeInfoTitle];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"hidden" object:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];
    [[WebServiceManager sharedManager]setnewServerIP:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupUI];

    shops.hidden = NO;
//    ShopObject *shopobj=[[DataManager sharedManager]getCurrentShop];
//    products = [[DataManager sharedManager] getOrderedProducts:nil  Shopid:shopobj.shopID Submit:0];
//    NSString *str = [NSString stringWithFormat:@"%d",products.count];
//    if (products.count==0) {
//        unsubcount.hidden = YES;
//    }
//    else
//    {
//        unsubcount.hidden = NO;
//        unsubcount.text = str;
//    }
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
   // [self.navigationController setNavigationBarHidden:YES animated:YES];
    shops.hidden = YES;
}

- (void)setupUI{
    
    if (hasSetupUI_) {
        return;
    }
    
    hasSetupUI_ = YES;
    //设置背景图
#ifdef DHH_iOS
    UIImageView *bgView = [[UIHelper getInstance] createViewByImageName:@"main_background_iphone.jpg"];
//    NSArray *picArray = [NSArray arrayWithObjects:@"main_recommend_iphone.png",
//                         @"main_product_iphone.png",@"main_analysis_iphone.png",
//                         @"main_statistic_iphone.png",@"main_collect_iphone.png",@"main_help_iphone.png", nil];
//    UIView *leftSlide = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, self.view.height-44)];
    bgView.frame = self.view.bounds;
    bgView.userInteractionEnabled = YES;
    [self.view addSubview:bgView];
    
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"main_message_iphone.png"];
    UIImageView *imageview = [[UIImageView alloc]initWithImage:img];
    imageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        imageview.center = CGPointMake(self.view.width/2, 25+64);
    }
    else
    {
        imageview.center = CGPointMake(self.view.width/2, 25);
    }
    [bgView addSubview:imageview];
    
    ShopObject *shopobj=[[DataManager sharedManager]getCurrentShop];
    NSMutableDictionary *dic = [[DataManager sharedManager]getAllOrderSum:shopobj.shopID];
    NSString *count=[dic objectForKey:@"cnt"];
    NSString *price=[dic objectForKey:@"totalmoney"];
    totalprice = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, img.size.height/2)];
    totalprice.backgroundColor = [UIColor clearColor];
    NSString *str = [NSString stringWithFormat:@"订单总金额:%@",price];
    totalprice.text = str;
    totalprice.textColor = [UIColor whiteColor];
    [imageview addSubview:totalprice];
    
    totalcount = [[UILabel alloc]initWithFrame:CGRectMake(0, img.size.height/2, 200, img.size.height/2)];
    totalcount.backgroundColor = [UIColor clearColor];
    str = [NSString stringWithFormat:@"订单总数量:%@",count];
    totalcount.text = str;
    totalcount.textColor = [UIColor whiteColor];
    [imageview addSubview:totalcount];
    /*
    UIButton *setting = [UIButton buttonWithType:UIButtonTypeCustom];
    setting.backgroundColor=[UIColor grayColor];
    setting.frame = CGRectMake(0, 0, 50, 20);
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        setting.center = CGPointMake(self.view.width/2, 50+64);
    }
    else
    {
        setting.center = CGPointMake(self.view.width/2, 50);
    }
    [setting setTitle:@"配比" forState:UIControlStateNormal];
    [setting addTarget:self action:@selector(setting:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:setting];
    */

    products = [[DataManager sharedManager] getOrderedProducts:nil  Shopid:shopobj.shopID Submit:0];
    UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, self.view.height-110)];
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        scroll.top = 60+64;
    }
    else
    {
        scroll.top = 60;
    }
    scroll.contentSize = CGSizeMake(320, 480);
    [bgView addSubview:scroll];
    int bottom;
    for (int i = 0; i<6; i++) {
        UIImage *img = [[UIImage alloc]init];
        if (i==0) {
            img = [[UIHelper getInstance] getBundleImage:@"main_recommend_ipad.png"];
        }
        else if(i==1)
        {
            img = [[UIHelper getInstance] getBundleImage:@"main_product_ipad.png"];
        }
        else if(i==2)
        {
            img = [[UIHelper getInstance] getBundleImage:@"main_statistic_ipad.png"];
        }
        else if(i==3)
        {
            img = [[UIHelper getInstance] getBundleImage:@"main_analysis_ipad.png"];
        }
        else if(i==4)
        {
            img = [[UIHelper getInstance] getBundleImage:@"main_collect.png"];
        }
        else if(i==5)
        {
            img = [[UIHelper getInstance] getBundleImage:@"main_help_ipad.png"];
        }
        NSArray *array = [NSArray arrayWithObjects:@"重点搭配",@"商品订购",@"订货管理",
                          @"报表统计",@"我的收藏",@"用户服务", nil];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 140, 111);
        btn.backgroundColor = [UIColor colorWithRed:187/255.0 green:89/255.0 blue:61/255.0 alpha:1.0];
        [btn setImage:img forState:UIControlStateNormal];
        [btn setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 30, 20, 30);
        btn.titleEdgeInsets = UIEdgeInsetsMake(btn.height-35, -img.size.width, 0, 0);
        btn.center = CGPointMake(self.view.width/2+(i%2*2-1)*78, 120*(i/2)+111/2);
        btn.tag = i;
        
        if (i==2) {
            unsubcount = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 40, 30)];
            NSString *str = [NSString stringWithFormat:@"%d",products.count];
            if (products.count==0) {
                unsubcount.hidden = YES;
            }
            else
            {
                unsubcount.hidden = NO;
                unsubcount.text = str;
            }
            unsubcount.adjustsFontSizeToFitWidth = YES;
            unsubcount.backgroundColor = [UIColor colorWithRed:143/255.0 green:90/255.0 blue:54/255.0 alpha:1];
            unsubcount.layer.cornerRadius = 10;
            unsubcount.layer.borderColor = [UIColor whiteColor].CGColor;
            unsubcount.layer.borderWidth = 3;
            unsubcount.textAlignment = UITextAlignmentCenter;
            unsubcount.textColor = [UIColor whiteColor];
            unsubcount.right = btn.width;
            unsubcount.top = 0;
            [btn addSubview:unsubcount];
        }
         
        [btn addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
        [scroll addSubview:btn];
        bottom = btn.bottom;
        /*
        UIImageView *imageview = [[UIImageView alloc]initWithImage:img];
        imageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
        imageview.center = CGPointMake(self.view.width/2+(i%2*2-1)*78, 110+120*(i/2));
        [bgView addSubview:imageview];
         */
    }
    UIButton* set = [UIButton buttonWithType:UIButtonTypeCustom];
    img = [[UIHelper getInstance] getBundleImage:@"set.png"];
    [set setBackgroundImage:img forState:UIControlStateNormal];
    set.frame = CGRectMake(10,70,img.size.width,img.size.height);
    set.tag=14;
    set.top = bottom+30;
    //setting.backgroundColor = [UIColor clearColor];
    //    [uploadbtn setTitle:@"aaa" forState:UIControlStateNormal];
    [set addTarget:self action:@selector(shops:) forControlEvents:UIControlEventTouchUpInside];
    [scroll addSubview:set];
#else
    UIImageView *bgView = [[UIHelper getInstance] createViewByImageName:@"main_background_ipad.jpg"];
    bgView.frame = CGRectMake(0, 0, 1024, 768);
    bgView.contentMode = UIViewContentModeScaleAspectFill;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0) {
        bgView.top=64;
    }

    NSArray *picArray = [NSArray arrayWithObjects:@"main_recommend_ipad.png",
                         @"main_product_ipad.png",@"main_statistic_ipad.png",
                         @"main_analysis_ipad.png",@"main_collect.png",@"main_help_ipad.png", nil];
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"main_message.png"];
    
    UIView *leftSlide;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0) {
        leftSlide = [[UIView alloc] initWithFrame:CGRectMake(0, 64, 160, self.view.height-64-img.size.height)];
    }
    else
    {
        leftSlide = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, self.view.height-44-img.size.height)];
    }
    [self.view addSubview:bgView];
    NSArray *array = [NSArray arrayWithObjects:@"重点搭配",@"商品订购",@"订货管理",
                      @"报表统计",@"我的收藏",@"用户服务", nil];
    
    float yOffset = 0;
    [self.view addSubview:leftSlide];
    leftSlide.backgroundColor = [[UIHelper getInstance] getColorbyRed:20 Green:20 Blue:20 Alpha:80];
    
    //为了校对订单使用，日常禁止使用
    orderview = [[OrdermessageView alloc]init];
    orderview.bottom = 768;
    orderview.left = 0;
    [self.navigationController.view addSubview:orderview];
    
    UIButton* uploadbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    uploadbtn.frame = CGRectMake(980,740,40,40);
    uploadbtn.left = 980;
    uploadbtn.top = 650;
    uploadbtn.backgroundColor = [UIColor clearColor];
//    [uploadbtn setTitle:@"aaa" forState:UIControlStateNormal];
    [self.view addSubview:uploadbtn];
    [uploadbtn addTarget:self action:@selector(uploadmiss:) forControlEvents:UIControlEventTouchUpInside];
    
    /////////////////////
    UIButton* set = [UIButton buttonWithType:UIButtonTypeCustom];
    img = [[UIHelper getInstance] getBundleImage:@"set.png"];
    [set setBackgroundImage:img forState:UIControlStateNormal];
    set.frame = CGRectMake(910,70,img.size.width,img.size.height);
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        set.top = 30+64;
    }
    else
    {
        set.top = 30;
    }
    set.tag=14;
    //setting.backgroundColor = [UIColor clearColor];
    //    [uploadbtn setTitle:@"aaa" forState:UIControlStateNormal];
    [set addTarget:self action:@selector(shops:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:set];
    
    
    
    
    for (int i = 0; i < array.count; i++) {
        UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
        
        UIImage *img = [[UIHelper getInstance] getBundleImage:[picArray objectAtIndex:i]];
        
        b.frame = CGRectMake(0, 0, leftSlide.width, (leftSlide.height-yOffset)/array.count);
        

        b.titleLabel.font = [[PMGlobal getInstance] getPadFont:20];
        
        float offset = (b.height-img.size.height)/2;
        //因为第一张重点搭配图片太长，做一个判断，来调整图片的位置
        if (offset < 25) {
            offset = 5;
        }
        
        [b setImage:img forState:UIControlStateNormal];
        [b setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];
        b.imageEdgeInsets = UIEdgeInsetsMake(b.height-img.size.height-40, (b.width-img.size.width)/2, 0, (b.width-img.size.width)/2);
        b.titleEdgeInsets = UIEdgeInsetsMake(b.height-35, -img.size.width, 0, 0);
        
        
        
        b.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
        
        b.top = b.height*i+yOffset;
        [leftSlide addSubview:b];
        [b addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
        b.tag = i;
        
        if (i==2) {
            unsubcount = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 40, 30)];
            NSString *str = [NSString stringWithFormat:@"%d",products.count];
            if(products.count==0)
            {
                unsubcount.hidden=YES;
            }
            else
            {
                unsubcount.hidden=NO;
                unsubcount.text = str;
            }
            unsubcount.adjustsFontSizeToFitWidth = YES;
            unsubcount.backgroundColor = [UIColor colorWithRed:143/255.0 green:90/255.0 blue:54/255.0 alpha:1];
            unsubcount.layer.cornerRadius = 10;
            unsubcount.layer.borderColor = [UIColor whiteColor].CGColor;
            unsubcount.layer.borderWidth = 3;
            unsubcount.textAlignment = UITextAlignmentCenter;
            unsubcount.textColor = [UIColor whiteColor];
            unsubcount.right = b.right;
            unsubcount.top = 0;
            [b addSubview:unsubcount];
        }
        
        UIView *sep = [[UIView alloc] initWithFrame:CGRectMake(0, 0, leftSlide.width, 1)];
        sep.backgroundColor = [[UIHelper getInstance] getColorbyRed:111 Green:113 Blue:115 Alpha:255];
        sep.top = b.bottom-1;
        sep.layer.shadowColor = [UIColor darkGrayColor].CGColor;
        sep.layer.shadowOffset = CGSizeMake(0, 0.5);
        sep.layer.shadowOpacity = 1.0;
        [leftSlide addSubview:sep];
    }
    
#endif 
    
    
    if (newshops.count>0) {
        ShopObject *shopobj=[newshops objectAtIndex:0];
        [self setNavTitle:shopobj.shopName];
        
        [[DataManager sharedManager]setCurrentShop:shopobj];
        
        [self updateOrder];
    }
}

#pragma mark 点击模块按钮的相应函数
- (void)clicked:(UIButton *)sender{
    shops.hidden = YES;
    switch (sender.tag) {
        case 0://重点搭配
        {
            SuitViewController *suit = [[SuitViewController alloc] init];
            [self.navigationController pushViewController:suit animated:YES];
        }
            
            break;
        case 1://商品订购
        {
            ProductViewController *product = [[ProductViewController alloc] init];
            [self.navigationController pushViewController:product animated:YES];
        }
            break;
        case 2://订货管理
        {
            ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
            if (!shopobj) {
                showMessage(@"用户没有与任何店铺关联");
                return;
            }
            StatisticViewController *statistic = [[StatisticViewController alloc] initWithNibName:nil bundle:nil tag:1];
            [self.navigationController pushViewController:statistic animated:YES];
        }
            break;
        case 3://报表统计
        {
            ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
            if (!shopobj) {
                showMessage(@"用户没有与任何店铺关联");
                return;
            }
            
            AnalysisViewController *analysis = [[AnalysisViewController alloc] init];
            [self.navigationController pushViewController:analysis animated:YES];
        }
            break;
        case 4://我的收藏
        {
            StatisticViewController *statistic = [[StatisticViewController alloc] initWithNibName:nil bundle:nil tag:2];
            [self.navigationController pushViewController:statistic animated:YES];
        }
            break;
        case 5://服务中心
        {
            HelpViewController *help = [[HelpViewController alloc]init];
            [self.navigationController pushViewController:help animated:YES];
        }
        default:
            break;
    }
}
#ifdef DHH_iOS
#else
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}

- (BOOL)shouldAutorotate{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}
#endif

- (void)app_has_expired{
    //[self.navigationController popViewControllerAnimated:YES];
    [self removeInfoTitle];
    [self performSelectorOnMainThread:@selector(ret) withObject:self waitUntilDone:YES];
}

//提交遗漏订单，日常不让使用
- (void)uploadmiss:(UIButton *)sender{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入密码" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil, nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].placeholder = @"请输入密码";
    alert.tag = 501;
    [alert show];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag==501) {
        if (buttonIndex==1) {
            NSString *pwd1 = [alertView textFieldAtIndex:0].text;
            if (![pwd1 isEqualToString:@"54321"]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误" message:@"请不要随意使用此功能,后果很严重" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                
                return;
            }else{
                
                [self performSelectorOnMainThread:@selector(gettotalorderInfo) withObject:nil waitUntilDone:YES];
            }
        }
    }
    else if(alertView.tag == 502){
        
        if (buttonIndex==1){
            
            
            [self performSelectorOnMainThread:@selector(uploadorder) withObject:nil waitUntilDone:YES];
        }
                
    }else if(alertView.tag == 503){
        if (buttonIndex==0) {
            [self back];
        }
    }else if(alertView.tag == 504){
        if (buttonIndex==1) {
            [self submitbyself];
        }
    }
    
}

-(void)gettotalorderInfo{
    
    NSDictionary* dict = [[DataManager sharedManager]getAllOrderSum:nil];
    
   [[WebServiceManager sharedManager] checktotal:[[DataManager sharedManager] getUserObject].userCode count:[dict objectForKey:@"cnt"] money:[dict objectForKey:@"totalmoney"] completion:^(NSArray *array){
       
       NSDictionary* serverdata = [array objectAtIndex:0];
       
       if ([[serverdata objectForKey:@"result"] isEqualToString:@"False"]) {
           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"前后台数据不一致" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil, nil];
           alert.tag = 502;
           [alert show];
       }
       else{
           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"前后台数据一致" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
           [alert show];
       }
    }];
}

- (void)uploadorder{
    [WaitTooles showHUD:@"正在处理本地订单..."];
    if ([[AppManager sharedManager]getSubmitStatus]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"后台正在自动提交订单请稍后" message:@"请重新登录" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    [[DataManager sharedManager]clearOrderUptime];
   
}
-(void)setting
{
    shops.hidden = YES;
    SettingmatchViewController *setting = [[SettingmatchViewController alloc]init];
    [self.navigationController pushViewController:setting animated:YES];
}
-(void)shops:(UIButton *)sender
{
    [items removeAllObjects];
    items = [NSMutableArray arrayWithCapacity:eSettingBar_Type_Total];
    if (sender.tag==13) {
        for (int i = 0; i<newshops.count; i++) {
            ShopObject *shopobj = [newshops objectAtIndex:i];
            NSString *border;
            if ([shopobj.bOrder boolValue] == YES) {
                border = [NSString stringWithFormat:@"可写"];
            }
            else
            {
                border = [NSString stringWithFormat:@"只读"];
            }
            NSString *str = [NSString stringWithFormat:@"%@%@(%@)",shopobj.shopID,shopobj.shopName,border];
            if (shopobj.bCheck==1) {
                str = [str stringByAppendingFormat:@"(审)"];
            }
            [items addObject:str];
        }
    }
    else
    {
        for (int i = 0;i<eSettingBar_Type_Total;i++) {
            [items addObject:[[PMGlobal getInstance]getSettingBar_TypeName:i]];
        }
    }
    
    controller = [[ShopViewController alloc] initWithStyle:UITableViewStylePlain items:items tag:sender.tag];
    
    FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
    
    //popover.arrowDirection = FPPopoverArrowDirectionAny;
    popover.tint = FPPopoverDefaultTint;
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        popover.contentSize = CGSizeMake(300, 500);
    }
    popover.arrowDirection = FPPopoverArrowDirectionUp;
    
    //sender is the UIButton view
    [popover presentPopoverFromView:sender];
}
#pragma mark 显示店铺
-(void)show:(NSNotification *)sender
{
    shops.hidden = NO;
}

#pragma mark 更新店铺标签
-(void)shoprefresh:(NSNotification *)sender
{
    int num = [sender.object intValue];
    ShopObject *shopobj = [newshops objectAtIndex:num];
    [[DataManager sharedManager]setCurrentShop:shopobj];
    [self setNavTitle:shopobj.shopName];

    [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh" object:nil];

    products = [[DataManager sharedManager] getOrderedProducts:nil  Shopid:shopobj.shopID Submit:0];
    NSString *str1 = [NSString stringWithFormat:@"%d",products.count];
    if (products.count==0) {
        unsubcount.hidden=YES;
    }
    else
    {
        unsubcount.hidden=NO;
        unsubcount.text = str1;
    }
    
    [self updateOrder];
}

#pragma mark 更新订单数量
-(void)ordernumrefresh:(NSNotification *)sender
{

    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
//    products = [[DataManager sharedManager] getOrderedProducts:nil  Shopid:shopobj.shopID Submit:0];
    int c = [[DataManager sharedManager] getUnloadProduct:shopobj.shopID];
    NSString *str1 = [NSString stringWithFormat:@"%d",c];
    if (c==0) {
        unsubcount.hidden = YES;
    }
    else
    {
        unsubcount.hidden = NO;
        unsubcount.text = str1;
    }
   // [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}
-(void)shopcheck
{
    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
    [[DataManager sharedManager]checkShop:shopobj];
}

-(void)vericheck
{
    [backview removeFromSuperview];
    backview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    backview.userInteractionEnabled=YES;
    [self.view addSubview:backview];
#ifdef DHH_iOS
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"vericheckbackview_iphone.png"];
    veriview = [[UIImageView alloc]initWithImage:img];
    veriview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    veriview.center=CGPointMake(160, 190);
    veriview.userInteractionEnabled=YES;
    // veriview.backgroundColor = [UIColor whiteColor];
    [backview addSubview:veriview];
#else
    UIImage *img = [[UIHelper getInstance] getBundleImage:@"vericheckbackview.png"];
    veriview = [[UIImageView alloc]initWithImage:img];
    veriview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    veriview.center=CGPointMake(512, 384);
    veriview.userInteractionEnabled=YES;
   // veriview.backgroundColor = [UIColor whiteColor];
    [backview addSubview:veriview];
#endif
    /*
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    title.centerX = veriview.width/4;
    title.top = 10;
    title.text=@"请输入用户名";
    title.font = [UIFont systemFontOfSize:14];
    title.textAlignment=UITextAlignmentCenter;
    [veriview addSubview:title];
    
    UILabel *title1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    title1.centerX = veriview.width/4;
    title1.top = title.bottom+10;
    title1.text=@"请输入密码";
    title1.font = [UIFont systemFontOfSize:14];
    title1.textAlignment=UITextAlignmentCenter;
    [veriview addSubview:title1];
     */
#ifdef DHH_iOS
    usercode = [[UITextField alloc]initWithFrame:CGRectMake(130, 40, 120, 40)];
    // usercode.top=title.top;
    // usercode.centerX = veriview.width/4*3;
    usercode.backgroundColor = [UIColor clearColor];
    usercode.delegate = self;
    // usercode.inputView = dummyView;
    usercode.textColor = [UIColor blackColor];
    usercode.textAlignment=UITextAlignmentLeft;
    usercode.placeholder = @"请输入用户名";
    usercode.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    usercode.returnKeyType = UIReturnKeyDone;
    usercode.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    usercode.tag=180003;
    [veriview addSubview:usercode];
    
    password = [[UITextField alloc]initWithFrame:CGRectMake(130, 85, 120, 30)];
   // password.top=title1.top;
   // password.centerX = veriview.width/4*3;
    password.backgroundColor = [UIColor clearColor];
    
    password.delegate = self;
    // password.inputView = dummyView;
    password.textColor = [UIColor blackColor];
    password.secureTextEntry = YES;
    password.textAlignment=UITextAlignmentLeft;
    password.placeholder = @"请输入密码";
    password.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    password.returnKeyType = UIReturnKeyDone;
    password.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    password.tag=180004;
    [veriview addSubview:password];
    
    img = [[UIHelper getInstance] getBundleImage:@"zbarlogin_iphone.png"];
    UIButton *zbar = [UIButton buttonWithType:UIButtonTypeCustom];
    [zbar setBackgroundImage:img forState:UIControlStateNormal];
    zbar.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    zbar.top=125;
    zbar.centerX = veriview.width/2+3;
    [zbar addTarget:self action:@selector(zbar:) forControlEvents:UIControlEventTouchUpInside];
    [veriview addSubview:zbar];
    
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    [sure setBackgroundImage:img forState:UIControlStateNormal];
    [sure setTitle:@"确定" forState:UIControlStateNormal];
    sure.frame = CGRectMake(0, 0, [[UIHelper getInstance] getBundleImage:@"detail_paste.png"].size.width, [[UIHelper getInstance] getBundleImage:@"detail_paste.png"].size.height);
    sure.top=zbar.bottom+12;
    sure.centerX = veriview.width/2-50;
    [sure addTarget:self action:@selector(sure) forControlEvents:UIControlEventTouchUpInside];
    [veriview addSubview:sure];
    
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setBackgroundImage:img forState:UIControlStateNormal];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    cancel.frame = CGRectMake(0, 0, [[UIHelper getInstance] getBundleImage:@"detail_paste.png"].size.width, [[UIHelper getInstance] getBundleImage:@"detail_paste.png"].size.height);
    cancel.top=zbar.bottom+12;
    cancel.centerX = veriview.width/2+50;
    [cancel addTarget:self action:@selector(cancelled) forControlEvents:UIControlEventTouchUpInside];
    [veriview addSubview:cancel];
    /*
    UITextField *count = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    count.top=title.top;
    count.centerX = veriview.width/2;
    count.backgroundColor = [UIColor grayColor];
    count.delegate = self;
    count.inputView = input;
    count.textColor = [UIColor whiteColor];
    count.textAlignment=UITextAlignmentCenter;
    count.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    count.tag=180003;
    [veriview addSubview:count];
     */
#else
   // UIView* dummyView = [[UIView alloc] initWithFrame:CGRectZero];
    usercode = [[UITextField alloc]initWithFrame:CGRectMake(200, 50, 200, 40)];
   // usercode.top=title.top;
   // usercode.centerX = veriview.width/4*3;
    usercode.backgroundColor = [UIColor clearColor];
    usercode.delegate = self;
   // usercode.inputView = dummyView;
    usercode.textColor = [UIColor blackColor];
    usercode.textAlignment=UITextAlignmentLeft;
    usercode.placeholder = @"请输入用户名";
    usercode.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    usercode.returnKeyType = UIReturnKeyDone;
    usercode.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    usercode.tag=180003;
    [veriview addSubview:usercode];
    
    password = [[UITextField alloc]initWithFrame:CGRectMake(200, 125, 200, 40)];
   // password.top=title1.top;
   // password.centerX = veriview.width/4*3;
    password.backgroundColor = [UIColor clearColor];
    password.secureTextEntry = YES;
    password.delegate = self;
   // password.inputView = dummyView;
    password.textColor = [UIColor blackColor];
    password.textAlignment=UITextAlignmentLeft;
    password.placeholder = @"请输入密码";
    password.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    password.returnKeyType = UIReturnKeyDone;
    password.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    password.tag=180004;
    [veriview addSubview:password];
    
    img = [[UIHelper getInstance] getBundleImage:@"zbarlogin.png"];
    UIButton *zbar = [UIButton buttonWithType:UIButtonTypeCustom];
    [zbar setImage:img forState:UIControlStateNormal];
    [zbar setTitle:@"二维码扫描" forState:UIControlStateNormal];
    zbar.frame = CGRectMake(0, 0, img.size.width, img.size.height);
    zbar.top=195;
    zbar.centerX = veriview.width/2+3;
    [zbar addTarget:self action:@selector(zbar:) forControlEvents:UIControlEventTouchUpInside];
    [veriview addSubview:zbar];
    
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    img = [[UIHelper getInstance] getBundleImage:@"anniu.png"];
    [sure setBackgroundImage:img forState:UIControlStateNormal];
    [sure setTitle:@"确定" forState:UIControlStateNormal];
    sure.frame = CGRectMake(0, 0, [[UIHelper getInstance] getBundleImage:@"detail_paste.png"].size.width, [[UIHelper getInstance] getBundleImage:@"detail_paste.png"].size.height);
    sure.top=zbar.bottom+30;
    sure.centerX = veriview.width/2-100;
    [sure addTarget:self action:@selector(sure) forControlEvents:UIControlEventTouchUpInside];
    [veriview addSubview:sure];
    
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setBackgroundImage:img forState:UIControlStateNormal];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    cancel.frame = CGRectMake(0, 0, [[UIHelper getInstance] getBundleImage:@"detail_paste.png"].size.width, [[UIHelper getInstance] getBundleImage:@"detail_paste.png"].size.height);
    cancel.top=zbar.bottom+30;
    cancel.centerX = veriview.width/2+100;
    [cancel addTarget:self action:@selector(cancelled) forControlEvents:UIControlEventTouchUpInside];
    [veriview addSubview:cancel];
#endif
}

-(void)sure
{
    if ([usercode.text isEqualToString:@""]||usercode.text==nil) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"请输入用户名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    else if ([password.text isEqualToString:@""]||password.text==nil) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"请输入密码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    else
    {
    [backview removeFromSuperview];
    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
    [[DataManager sharedManager]veriShop:usercode.text password:password.text shopid:shopobj.shopID];
    }
}

-(void)cancelled
{
    [backview removeFromSuperview];
}

-(void)zbar:(UIButton *)sender
{
    //    ZbarViewController *zbar = [[ZbarViewController alloc]init];
    //    [self.navigationController pushViewController:zbar animated:YES];
//    ZBarReaderViewController *reader = [ZBarReaderViewController new];
//    reader.readerDelegate = self;
//    reader.supportedOrientationsMask = ZBarOrientationMaskAll;
//#ifdef DHH_iOS
//    UIImage *img = [[UIHelper getInstance] getBundleImage:@"croprect_iphone.png"];
//    UIImageView *imageview = [[UIImageView alloc]initWithImage:img];
//    imageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    imageview.center = CGPointMake(160, 190);
//    [reader.view addSubview:imageview];
//    
//    img = [[UIHelper getInstance] getBundleImage:@"croptip_iphone.png"];
//    UIImageView *tipimageview = [[UIImageView alloc]initWithImage:img];
//    tipimageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    tipimageview.centerX = imageview.centerX;
//    tipimageview.top = imageview.bottom;
//    [reader.view addSubview:tipimageview];
//#else
//    UIImage *img = [[UIHelper getInstance] getBundleImage:@"croprect.png"];
//    UIImageView *imageview = [[UIImageView alloc]initWithImage:img];
//    imageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    imageview.center = CGPointMake(512, 368);
//    [reader.view addSubview:imageview];
//    
//    img = [[UIHelper getInstance] getBundleImage:@"croptip.png"];
//    UIImageView *tipimageview = [[UIImageView alloc]initWithImage:img];
//    tipimageview.frame = CGRectMake(0, 0, img.size.width, img.size.height);
//    tipimageview.centerX = imageview.centerX;
//    tipimageview.top = imageview.bottom;
//    [reader.view addSubview:tipimageview];
//#endif
//    CGRect scanMaskRect;
//    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
//    {
//        scanMaskRect = CGRectMake(0, 0, imageview.size.width, imageview.size.height);
//    }
//    else
//    {
//        scanMaskRect = CGRectMake(0, 0, 1024, 768);
//    }
//    reader.scanCrop = [self getScanCrop:scanMaskRect readerViewBounds:reader.view.bounds];
//    
//    ZBarImageScanner *scanner = reader.scanner;
//    
//    [scanner setSymbology: ZBAR_I25
//                   config: ZBAR_CFG_ENABLE
//                       to: 0];
//    
//    [self presentModalViewController: reader
//                            animated: YES];
}
//- (void) imagePickerController: (UIImagePickerController*) reader
// didFinishPickingMediaWithInfo: (NSDictionary*) info
//{
//    id<NSFastEnumeration> results =
//    [info objectForKey: ZBarReaderControllerResults];
//    ZBarSymbol *symbol = nil;
//    for(symbol in results)
//        break;
//    
//    zbarimageview.image =
//    [info objectForKey: UIImagePickerControllerOriginalImage];
//    
//    [reader dismissModalViewControllerAnimated: YES];
//    
//    //判断是否包含 头'http:'
//    NSString *regex = @"http+:[^\\s]*";
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
//    
//    //判断是否包含 头'ssid:'
//    NSString *ssid = @"ssid+:[^\\s]*";;
//    NSPredicate *ssidPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",ssid];
//    
//    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
//    [[DataManager sharedManager]veriShop:symbol.data shopid:shopobj.shopID];
//    
//    if ([predicate evaluateWithObject:zbarlabel.text]) {
//        
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil
//                                                        message:@"It will use the browser to this URL。"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"Close"
//                                              otherButtonTitles:@"Ok", nil];
//        alert.delegate = self;
//        alert.tag=1;
//        [alert show];
//        
//        
//        
//    }
//    else if([ssidPre evaluateWithObject:zbarlabel.text]){
//        
//        NSArray *arr = [zbarlabel.text componentsSeparatedByString:@";"];
//        
//        NSArray * arrInfoHead = [[arr objectAtIndex:0] componentsSeparatedByString:@":"];
//        
//        NSArray * arrInfoFoot = [[arr objectAtIndex:1] componentsSeparatedByString:@":"];
//        
//        
//        zbarlabel.text=
//        [NSString stringWithFormat:@"ssid: %@ \n password:%@",
//         [arrInfoHead objectAtIndex:1],[arrInfoFoot objectAtIndex:1]];
//        
//        
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:zbarlabel.text
//                                                        message:@"The password is copied to the clipboard , it will be redirected to the network settings interface"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"Close"
//                                              otherButtonTitles:@"Ok", nil];
//        
//        
//        alert.delegate = self;
//        alert.tag=2;
//        [alert show];
//        
//        UIPasteboard *pasteboard=[UIPasteboard generalPasteboard];
//        //        然后，可以使用如下代码来把一个字符串放置到剪贴板上：
//        pasteboard.string = [arrInfoFoot objectAtIndex:1];
//        
//        
//    }
//    [zbarreader removeFromParentViewController];
//}
#pragma mark -
//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    // if(offset > 0)
#ifdef DHH_iOS
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
    {
        self.view.frame = CGRectMake(0.0f, -80+64, self.view.frame.size.width, self.view.frame.size.height);
    }
    else
    {
        self.view.frame = CGRectMake(0.0f, -80, self.view.frame.size.width, self.view.frame.size.height);
    }
#else
    self.view.frame = CGRectMake(0.0f, -150, self.view.frame.size.width, self.view.frame.size.height);
#endif
    //  login.frame = CGRectMake(0.0f, -96, imageview.frame.size.width, imageview.frame.size.height);
    //  textimageview.center = CGPointMake(self.view.width/2, 140);
    //  text.top = 83;
    // logintext.top = text.bottom+4;
    // passwordtext.top = logintext.bottom+4;
    // signIn.top = passwordtext.bottom +10;
    
    [UIView commitAnimations];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [usercode resignFirstResponder];
    [password resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
    return YES;
}
-(void)keyboardWillHide:(NSNotification *)sender
{
    [usercode resignFirstResponder];
    [password resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr {
    [usercode resignFirstResponder];
    [password resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}

#pragma mark 消息更新弹出框
-(void)showtip:(NSNotification *)sender
{
    NSArray *tips = [[DataManager sharedManager]getTipsarray];
    if (tips.count==0) {
        return;
    }
    NSDictionary *tipdic = [tips objectAtIndex:tips.count-1];

    [self performSelectorOnMainThread:@selector(addTipView:) withObject:tipdic waitUntilDone:YES];
    
}

- (void)addTipView:(NSDictionary *)dic{
    TipView *tipview = [[TipView alloc]initWithdic:dic];
    [self.navigationController.view addSubview:tipview];
}

#pragma mark 设置按钮poperview框点击通知
-(void)set:(NSNotification *)sender
{
    int num = [sender.object intValue];
    
    switch (num) {
        case eSettingBar_Type_Update:
            showMessage(@"开始检测更新");
            [[AppManager sharedManager] startAutoUpdateSession];
            break;
#ifdef SHOP_VERIFY_ENABLE
        case eSettingBar_Type_Shopcheck:
            [self b2click:nil];
            break;
        case eSettingBar_Type_Shopveri:
            [self b3click:nil];
            break;
#endif
        case eSettingBar_Type_Version:
            break;
        case eSettingBar_Type_Admin:
        {
            AdministratorViewController *v = [[AdministratorViewController alloc] init];
            [self.navigationController pushViewController:v animated:YES];
        }
            break;
            
        default:
            break;
    }
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
    
    return;
    
    
    
    
    if (num==1) {
        [self setting];
    }

    else if(num==0){
//        [[AppManager sharedManager] updateDatabase];
        
        
        [[AppManager sharedManager] pauseAutoSubmitSession];
        [[AppManager sharedManager] pauseAutoUpdateSession];
        
        [WaitTooles showHUD:@"正在下载所有的商品资料，这个过程需要比较长的时间"];
        
        [[DataManager sharedManager] forceUpdate:^(id res){
            [WaitTooles removeHUD];
            [[AppManager sharedManager] resumeAutoSubmitSession];
            [[AppManager sharedManager] resumeAutoUpdateSession];
        }];
        
        
        
//        [WaitTooles showHUD:@"正在重新下载商品基础档案和配装数据"];
//        [[AppManager sharedManager] forceUpdate:^(id res){
//            [WaitTooles removeHUD];
//            2
//
//        }];
    }else if(num==2){
        exit(0);
    }else if(num==4){
        [[AppManager sharedManager] forceSubmitOrder:^(id res){
            
        }];
    }else if(num==3){
        
        ShopObject *shopobj=[[DataManager sharedManager]getCurrentShop];
        if ([[DataManager sharedManager] getOrderedProducts:nil Shopid:shopobj.shopID Submit:0].count>0) {
            showMessage(@"您还有未上传订单，请先上传订单");
        }else{
            [WaitTooles showHUD:@"正在更新您的订单"];
            
            [[AppManager sharedManager] pauseAutoUpdateSession];
            [[AppManager sharedManager] pauseAutoSubmitSession];
            
            [[DataManager sharedManager] copyDatabase];
            
            [[DataManager sharedManager] deleteTableByShop:@"g_meeting" shop:shopobj.shopID];
            [[DataManager sharedManager] updateOrder:^(id res){

                showMessage(@"订单更新成功");
                [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh" object:nil];
                [[AppManager sharedManager] resetAutoSubmitSession];
                [[AppManager sharedManager] resetAutoUpdateSession];
            }];
        }
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
    /*
    UIButton *shopcheck = [UIButton buttonWithType:UIButtonTypeCustom];
    shopcheck.backgroundColor=[UIColor grayColor];
    shopcheck.frame = CGRectMake(0, 0, 100, 20);
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        shopcheck.center = CGPointMake(self.view.width/2-70, 100+32);
    }
    else
    {
        shopcheck.center = CGPointMake(self.view.width/2-70, 100);
    }
    [shopcheck setTitle:@"店铺检查" forState:UIControlStateNormal];
    [shopcheck addTarget:self action:@selector(shopcheck:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shopcheck];

    UIButton *vericheck = [UIButton buttonWithType:UIButtonTypeCustom];
    vericheck.backgroundColor=[UIColor grayColor];
    vericheck.frame = CGRectMake(0, 0, 100, 20);
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        vericheck.center = CGPointMake(self.view.width/2+70, 100+32);
    }
    else
    {
        vericheck.center = CGPointMake(self.view.width/2+70, 100);
    }
    [vericheck setTitle:@"店铺审核" forState:UIControlStateNormal];
    [vericheck addTarget:self action:@selector(vericheck:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:vericheck];
    
    UIButton *setting = [UIButton buttonWithType:UIButtonTypeCustom];
    setting.backgroundColor=[UIColor grayColor];
    setting.frame = CGRectMake(0, 0, 50, 20);
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        setting.center = CGPointMake(self.view.width/2, 50+32);
    }
    else
    {
        setting.center = CGPointMake(self.view.width/2, 50);
    }
    [setting setTitle:@"配比" forState:UIControlStateNormal];
    [setting addTarget:self action:@selector(setting:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:setting];
*/
}
-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    CGFloat x,y,width,height;
    
    x = rect.origin.x / readerViewBounds.size.width;
    y = rect.origin.y / readerViewBounds.size.height;
    width = rect.size.width / readerViewBounds.size.width;
    height = rect.size.height / readerViewBounds.size.height;
    
    return CGRectMake(x, y, width, height);
}

-(void)submitbyself{
    // if ([[AppManager sharedManager]getSubmitStatus]) {
    //     return;
    // }
    
    [WaitTooles showHUD:@"正在提交订单"];
//    [[AppManager sharedManager] forceSubmitOrder:^(id res){
//        [WaitTooles removeHUD];
//    }];
    [[AppManager sharedManager] forceSubmitAllOrder:^(id res){
        [WaitTooles removeHUD];
    }];
}


#pragma mark 订单审核与订单检查
-(void)b2click:(UIButton *)sender
{
    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
    products = [[DataManager sharedManager] getOrderedProducts:nil  Shopid:shopobj.shopID Submit:0];
    if (products.count!=0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"还有未上传的订单" message:@"是否上传" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"上传", nil];
        [alert show];
        alert.tag = 504;
    }
    else
    {
        
        [WaitTooles showHUD:@"正在检查订单数据一致性"];
        [[DataManager sharedManager] verifyOrderWithServer:^(id res){
            [WaitTooles removeHUD];
            if (res) {
                [self shopcheck];
            }
            
        }];

    }
}

-(void)b3click:(UIButton *)sender
{
    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
    products = [[DataManager sharedManager] getOrderedProducts:nil  Shopid:shopobj.shopID Submit:0];
    if (products.count!=0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"还有未上传的订单" message:@"是否上传" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"上传", nil];
        [alert show];
        alert.tag = 504;
    }
    else
    {
        [WaitTooles showHUD:@"正在检查订单数据一致性"];
        [[DataManager sharedManager] verifyOrderWithServer:^(id res){
            [WaitTooles removeHUD];
            if (res) {
                [self vericheck];
            }
            
        }];
        
    }
}
@end
